package com.magicrule.car.systemManage.configClass.shiro;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.ByteSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.magicrule.car.systemManage.model.User;

/**
 * 
 * 用户密码加密工具类
 * @author hebb
 *
 */
public class PasswordHelper {

	protected static Logger log = LoggerFactory.getLogger(PasswordHelper.class);

	private RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
	private String algorithmName = "MD5"; //使用MD5加密
	private final int hashIterations = 2; //加密两次

	public User encryptPassword(User user) {

		/**
		 * 生成具有随机数据的固定长度的字节数组，通常用于生成盐、初始化向量或其他种子数据。
		 */
		user.setSalt(randomNumberGenerator.nextBytes().toHex());

		/**
		 * 将用户的注册密码经过散列算法替换成一个不可逆的新密码保存进数据，散列过程使用了盐 credentialsSalt=userName+salt
		 */
		String newPassword = new SimpleHash(algorithmName, user.getPassword(),
				ByteSource.Util.bytes(user.getCredentialsSalt()), hashIterations).toHex();
		user.setPassword(newPassword);
		return user;
	}

}